import { useCallback, useState } from 'react';
import { Modal, Tree, Button } from 'antd';
import type { DataNode } from 'antd/es/tree';
import { Icon } from '@iconify/react';
import { DynamicCrudPage } from '@/components';
import type { TableConfig } from '@/components/DynamicTable/types';
import { getTableConfigByCode } from '@/api/tableConfig';
import { transformTableConfig } from '@/utils/tableConfigTransform';
import { transformEditData, transformSubmitData } from '@/utils/formDataTransform';
import { getRoles, createRole, updateRole, deleteRole, getRolePermissions, assignPermissions } from './api';
import * as permissionApi from '@/api/permission';
import type { Role, Permission } from '@/types';
import { useAuthStore } from '@/stores/useAuthStore';

const RoleManagement = () => {
  const { hasPermission } = useAuthStore();
  
  // 权限分配相关状态
  const [permissionVisible, setPermissionVisible] = useState(false);
  const [currentRole, setCurrentRole] = useState<Role | undefined>();
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);
  const [permissionLoading, setPermissionLoading] = useState(false);

  const fetchConfigApi = useCallback(async (): Promise<TableConfig> => {
    const configRecord = await getTableConfigByCode('roles');
    if (!configRecord) {
      throw new Error('角色表格配置不存在');
    }
    // 添加自定义操作列
    const config = transformTableConfig(configRecord);
    return config;
  }, []);

  // 获取所有权限
  const fetchPermissions = async () => {
    try {
      const response = await permissionApi.getPermissions({ pageSize: 10000 });
      if (response.data.success) {
        setPermissions(response.data.data);
      }
    } catch (error) {
      console.error('Failed to fetch permissions:', error);
    }
  };

  // 加载权限数据
  useState(() => {
    fetchPermissions();
  });

  // 处理权限分配
  const handleAssignPermissions = async (record: Role) => {
    setCurrentRole(record);
    setPermissionVisible(true);
    setPermissionLoading(true);
    
    try {
      const response = await getRolePermissions(record.id);
      if (response.data.success) {
        setSelectedPermissions(response.data.data);
      }
    } catch (error) {
      console.error('Failed to fetch role permissions:', error);
    } finally {
      setPermissionLoading(false);
    }
  };

  const handleSavePermissions = async () => {
    if (!currentRole) return;

    setPermissionLoading(true);
    try {
      await assignPermissions({
        roleId: currentRole.id,
        permissionIds: selectedPermissions,
      });
      setPermissionVisible(false);
    } catch (error) {
      console.error('Failed to assign permissions:', error);
    } finally {
      setPermissionLoading(false);
    }
  };

  // 转换权限为树形数据
  const permissionTreeData: DataNode[] = (() => {
    const resourceMap = new Map<string, Permission[]>();
    
    permissions.forEach(permission => {
      const resourceParts = permission.resource.split(':');
      const resourceKey = resourceParts.slice(0, 2).join(':');
      
      if (!resourceMap.has(resourceKey)) {
        resourceMap.set(resourceKey, []);
      }
      resourceMap.get(resourceKey)!.push(permission);
    });

    return Array.from(resourceMap.entries()).map(([resourceKey, perms]) => {
      const moduleName = perms[0]?.description?.split(' - ')[0] || resourceKey;
      
      return {
        title: moduleName,
        key: resourceKey,
        children: perms.map(p => ({
          title: p.description || `${p.resource}:${p.action}`,
          key: p.id,
        })),
      };
    });
  })();

  const wrappedUpdateApi = async (data: any) => {
    const { id, ...updateData } = data;
    return updateRole({ id, ...updateData });
  };

  const handleTransformFormData = (data: any, mode: 'create' | 'update') => {
    return transformSubmitData(data);
  };

  // 自定义删除前检查
  const handleBeforeDelete = (record: any): boolean => {
    if (record.isSystem) {
      Modal.warning({
        title: '系统角色不允许删除',
        content: '系统内置角色受保护，无法删除。',
      });
      return false;
    }
    return true;
  };

  return (
    <>
      <DynamicCrudPage
        fetchConfigApi={fetchConfigApi}
        fetchApi={getRoles}
        createApi={createRole}
        updateApi={wrappedUpdateApi}
        deleteApi={deleteRole}
        transformEditData={transformEditData}
        transformFormData={handleTransformFormData}
        title="角色管理"
      />
      
      {/* 权限分配弹窗 */}
      <Modal
        title={`分配权限 - ${currentRole?.name}`}
        open={permissionVisible}
        onOk={handleSavePermissions}
        onCancel={() => setPermissionVisible(false)}
        width={600}
        confirmLoading={permissionLoading}
        bodyStyle={{
          maxHeight: '60vh',
          overflowY: 'auto',
          padding: '24px',
        }}
      >
        <Tree
          checkable
          defaultExpandAll
          treeData={permissionTreeData}
          checkedKeys={selectedPermissions}
          onCheck={(checkedKeys) => {
            setSelectedPermissions(checkedKeys as string[]);
          }}
        />
      </Modal>
    </>
  );
};

export default RoleManagement;
